package com.qs.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qs.constant.UserGoodsLogConstant;
import com.qs.mapper.*;
import com.qs.pojo.dto.CommentDto;
import com.qs.pojo.entity.*;
import com.qs.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2023-11-25
 */
@Service
@RequiredArgsConstructor
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    private final UserMapper userMapper;

    private final UserGoodsLogMapper userGoodsLogMapper;

    private final StoreMapper storeMapper;

    private final GoodsMapper goodsMapper;

    @Override
    public List<CommentDto> listComments(Integer id) {
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id",id);
        wrapper.orderByDesc("create_time");
        List<Comment> comments = baseMapper.selectList(wrapper);
        List<CommentDto> list = new ArrayList<>();
        if(!CollectionUtils.isEmpty(comments)){
            comments.stream().forEach(comment -> {
                User user = userMapper.selectById(comment.getUserId());
                CommentDto commentDto = new CommentDto();
                commentDto.setAvatar(user.getAvatar());
                commentDto.setNickName(user.getNickName());
                commentDto.setId(comment.getId());
                commentDto.setComment(comment.getComment());
                String createTime = LocalDateTimeUtil.format(LocalDateTimeUtil.parse(comment.getCreateTime().toString()), DatePattern.NORM_DATETIME_MINUTE_PATTERN);
                commentDto.setCreateTime(createTime);
                list.add(commentDto);
            });
            return list;
        }
        return null;
    }

    @Override
    public void saveComment(Comment comment) {
        baseMapper.insert(comment);
        //将qs_user_goods_log表中的商品状态修改为已评价
        QueryWrapper<UserGoodsLog> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id",comment.getGoodsId());
        wrapper.eq("user_id",comment.getUserId());
        wrapper.eq("order_id",comment.getOrderId());
        List<UserGoodsLog> userGoodsLogs = userGoodsLogMapper.selectList(wrapper);
        if(!CollectionUtils.isEmpty(userGoodsLogs)){
            userGoodsLogs.stream().forEach(item -> {
                userGoodsLogMapper.updateById(item.setIsComment(UserGoodsLogConstant.DO_COMMENT));
            });
        }
    }

    @Override
    public Map<String, Object> backendListComments(Integer pageNo, Integer pageSize, Integer userId) {
        Page<Comment> pageInfo = new Page<>(pageNo,pageSize);
        //获取店铺id
        List<Integer> storeIds = storeMapper.selectList(new QueryWrapper<Store>().eq("user_id", userId)).stream().map(item -> item.getId()).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(storeIds)){
            List<Integer> goodsId = this.findGoodsId(storeIds);
            //根据商品id进行分页查询
            if(!CollectionUtils.isEmpty(goodsId)){
                Page<Comment> selectPage = baseMapper.selectPage(pageInfo, new QueryWrapper<Comment>().in("goods_id", goodsId));
                List<Comment> comments = selectPage.getRecords();
                List<CommentDto> result = new ArrayList<>();
                if(!CollectionUtils.isEmpty(comments)){
                    comments.stream().forEach(item -> {
                        User user = userMapper.selectById(item.getUserId());
                        Goods goods = goodsMapper.selectById(item.getGoodsId());
                        CommentDto commentDto = new CommentDto();
                        commentDto.setGoodsName(goods.getName());
                        commentDto.setNickName(user.getNickName());
                        commentDto.setId(item.getId());
                        commentDto.setScore(item.getScore());
                        commentDto.setComment(item.getComment());
                        commentDto.setGoodsImage(goods.getImage());
                        result.add(commentDto);
                    });
                }
                Map<String, Object> map = new HashMap<>();
                map.put("total",selectPage.getTotal());
                map.put("data",result);
                return map;
            }
        }
        return null;
    }

    private List<Integer> findGoodsId(List<Integer> storeIds) {
        return goodsMapper.selectList(new QueryWrapper<Goods>()
                        .in("store_id", storeIds))
                .stream().map(item -> item.getId()).collect(Collectors.toList());
    }
}
